export const getLocaleTitle = (locale: string, meta: any) => {
  // debugger
  if (!locale || !meta) return "";
  const normLocale = locale.replace("-", "_").toLowerCase();
  // 简体中文

  if (normLocale == "zh" || normLocale == "zh_cn") {
    return meta.title || "";
  }
  // 繁体中文
  if (normLocale == "zh_tw" || normLocale == "zh_hk") {
    return meta.zh_hk_title || "";
  }
  // 英文
  if (normLocale.startsWith("en")) {
    return meta.en_title || "";
  }
  // 兜底
  return meta.title || "";
};

export const isCnLocale = (locale: string) => {
  if (!locale) return false;
  const normLocale = locale.replace("-", "_").toLowerCase();
  return normLocale === "zh_tw" || normLocale === "zh_hk";
};

export const validateEmail = (email: string): boolean => {
  if (!email) return false;
  const emailRegex =
    /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return emailRegex.test(String(email).toLowerCase());
};

export const formatDate = (timestamp: any) => {
  if (!timestamp) return "";
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");

  return `${year}/${month}/${day}`;
};

/**
 * 将 UTC 时间转换为本地时间并格式化为日期字符串
 * @param utcDateString UTC 时间字符串
 * @returns 本地化的日期字符串 (YYYY/MM/DD)
 */
export const formatUTCToLocalDate = (utcDateString: any) => {
  if (!utcDateString) return "";

  // 创建 UTC 时间的 Date 对象
  const utcDate = new Date(utcDateString);

  // 检查日期是否有效
  if (isNaN(utcDate.getTime())) {
    return "";
  }

  // 获取本地时间
  const localDate = new Date(utcDate.getTime());

  const year = localDate.getFullYear();
  const month = String(localDate.getMonth() + 1).padStart(2, "0");
  const day = String(localDate.getDate()).padStart(2, "0");

  return `${year}/${month}/${day}`;
};
type InputDate = Date | string | number;

export const formatDateTime = (time: InputDate) => {
  if (!time) return "";
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hour = String(date.getHours()).padStart(2, "0");
  const minute = String(date.getMinutes()).padStart(2, "0");

  return `${year}/${month}/${day}-${hour}:${minute}`;
};

export const formatDateArea = (start: InputDate, end: InputDate) => {
  const padZero = (num: number) => num.toString().padStart(2, "0");

  // 转换为 Date 对象并验证有效性
  const startDate = new Date(start);
  const endDate = new Date(end);
  if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
    throw new Error("传入的开始时间或结束时间无效");
  }

  // 提取年、月、日（月份+1，因为 Date 月份是 0-11）
  const startYear = startDate.getFullYear();
  const startMonth = padZero(startDate.getMonth() + 1);
  const startDay = padZero(startDate.getDate());

  const endYear = endDate.getFullYear();
  const endMonth = padZero(endDate.getMonth() + 1);
  const endDay = padZero(endDate.getDate());

  // 同一年简化年份，不同年显示完整年份
  if (startYear === endYear) {
    return `${startYear}/${startMonth}/${startDay}~${endMonth}/${endDay}`;
  } else {
    return `${startYear}/${startMonth}/${startDay}~${endYear}/${endMonth}/${endDay}`;
  }
};

// ... existing code ...

/**
 * 精确加法运算，解决浮点数精度问题
 * @param a 第一个数
 * @param b 第二个数
 * @returns 精确的加法结果
 */
export const preciseAdd = (a: number, b: number): number => {
  const num1 = Number(a);
  const num2 = Number(b);

  if (isNaN(num1) || isNaN(num2)) {
    throw new Error("参数必须是有效数字");
  }

  // 获取小数位数
  const getDecimalPlaces = (num: number): number => {
    const str = num.toString();
    const decimalIndex = str.indexOf(".");
    return decimalIndex === -1 ? 0 : str.length - decimalIndex - 1;
  };

  const decimalPlaces = Math.max(
    getDecimalPlaces(num1),
    getDecimalPlaces(num2)
  );
  const multiplier = Math.pow(10, decimalPlaces);

  return (
    (Math.round(num1 * multiplier) + Math.round(num2 * multiplier)) / multiplier
  );
};

/**
 * 精确减法运算，解决浮点数精度问题
 * @param a 被减数
 * @param b 减数
 * @returns 精确的减法结果
 */
export const preciseSubtract = (a: number, b: number): number => {
  const num1 = Number(a);
  const num2 = Number(b);

  if (isNaN(num1) || isNaN(num2)) {
    throw new Error("参数必须是有效数字");
  }

  // 获取小数位数
  const getDecimalPlaces = (num: number): number => {
    const str = num.toString();
    const decimalIndex = str.indexOf(".");
    return decimalIndex === -1 ? 0 : str.length - decimalIndex - 1;
  };

  const decimalPlaces = Math.max(
    getDecimalPlaces(num1),
    getDecimalPlaces(num2)
  );
  const multiplier = Math.pow(10, decimalPlaces);

  return (
    (Math.round(num1 * multiplier) - Math.round(num2 * multiplier)) / multiplier
  );
};

/**
 * 精确乘法运算，解决浮点数精度问题
 * @param a 第一个数
 * @param b 第二个数
 * @returns 精确的乘法结果
 */
export const preciseMultiply = (a: number, b: number): number => {
  const num1 = Number(a);
  const num2 = Number(b);

  if (isNaN(num1) || isNaN(num2)) {
    throw new Error("参数必须是有效数字");
  }

  // 获取小数位数
  const getDecimalPlaces = (num: number): number => {
    const str = num.toString();
    const decimalIndex = str.indexOf(".");
    return decimalIndex === -1 ? 0 : str.length - decimalIndex - 1;
  };

  const decimalPlaces1 = getDecimalPlaces(num1);
  const decimalPlaces2 = getDecimalPlaces(num2);
  const totalDecimalPlaces = decimalPlaces1 + decimalPlaces2;

  const multiplier1 = Math.pow(10, decimalPlaces1);
  const multiplier2 = Math.pow(10, decimalPlaces2);

  return (
    (Math.round(num1 * multiplier1) * Math.round(num2 * multiplier2)) /
    Math.pow(10, totalDecimalPlaces)
  );
};

/**
 * 精确除法运算，解决浮点数精度问题
 * @param a 被除数
 * @param b 除数
 * @param precision 精度位数，默认为10位小数
 * @returns 精确的除法结果
 */
export const preciseDivide = (
  a: number,
  b: number,
  precision: number = 10
): number => {
  const num1 = Number(a);
  const num2 = Number(b);

  if (isNaN(num1) || isNaN(num2)) {
    throw new Error("参数必须是有效数字");
  }

  if (num2 === 0) {
    throw new Error("除数不能为零");
  }

  // 获取小数位数
  const getDecimalPlaces = (num: number): number => {
    const str = num.toString();
    const decimalIndex = str.indexOf(".");
    return decimalIndex === -1 ? 0 : str.length - decimalIndex - 1;
  };

  const decimalPlaces1 = getDecimalPlaces(num1);
  const decimalPlaces2 = getDecimalPlaces(num2);
  const maxDecimalPlaces = Math.max(decimalPlaces1, decimalPlaces2);
  const multiplier = Math.pow(10, maxDecimalPlaces);

  const result = Math.round(num1 * multiplier) / Math.round(num2 * multiplier);

  // 使用 toFixed 确保精度，然后转换为数字
  return Number(result.toFixed(precision));
};

/**
 * 批量精确运算工具
 * @param numbers 数字数组
 * @param operator 运算符 ('add' | 'subtract' | 'multiply' | 'divide')
 * @param precision 精度位数（仅除法使用）
 * @returns 运算结果
 */
export const preciseCalculate = (
  numbers: number[],
  operator: "add" | "subtract" | "multiply" | "divide",
  precision?: number
): number => {
  if (!numbers || numbers.length === 0) {
    throw new Error("数字数组不能为空");
  }

  if (numbers.length === 1) {
    return numbers[0];
  }

  let result = numbers[0];

  for (let i = 1; i < numbers.length; i++) {
    switch (operator) {
      case "add":
        result = preciseAdd(result, numbers[i]);
        break;
      case "subtract":
        result = preciseSubtract(result, numbers[i]);
        break;
      case "multiply":
        result = preciseMultiply(result, numbers[i]);
        break;
      case "divide":
        result = preciseDivide(result, numbers[i], precision);
        break;
      default:
        throw new Error("不支持的运算符");
    }
  }

  return result;
};
